/**
 * api
 */

const URL = require('url');
const Axios = require('axios').Axios;
const defaultSignature = require('./signature');

class SignApi extends Axios {
    constructor(apiUrl = '', {
        signature = defaultSignature,
        appId = 'app_id',
        appSecret = ''
    } = {}) {
        super({
            baseURL: apiUrl
        });

        // signature
        this.interceptors.request.use(config => {
            const timestamp = Math.floor(Date.now() / 1000);
            const urlData = URL.parse(config.url, true);
            const query = Object.assign({},
                urlData.query,
                config.params
            );

            const sign = signature({
                path: urlData.pathname,
                method: config.method,
                body: config.data,
                query: query,
                timestamp,
                appSecret,
                appId
            });

            // set header
            Object.assign(config.headers.common, {
                'X-Timestamp': timestamp,
                'X-Signature': sign,
                'X-Appid': appId
            });

            return config;
        });
    }
};

module.exports = SignApi;
